package com.it.gateway.exception;


import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.WebProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.*;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.Map;

/**
 * 网关全局异常处理
 */

@Configuration
public class GlobalErrorExceptionHandler {

    /**
     * 创建ErrorWebExceptionHandler Bean
     */
    @Bean
    @Order(-1) // 调整优先级
    public ExceptionHandler errorWebExceptionHandler(ErrorAttributes errorAttributes,
                                                    WebProperties webProperties,
                                                    ApplicationContext applicationContext,
                                                    ServerCodecConfigurer configurer) {
        ExceptionHandler exceptionHandler = new ExceptionHandler(
                errorAttributes,
                webProperties.getResources(),
                new ErrorProperties(),
                applicationContext);
        exceptionHandler.setMessageReaders(configurer.getReaders());
        exceptionHandler.setMessageWriters(configurer.getWriters());
        return exceptionHandler;
    }

    /**
     * 自定义异常处理器
     */
    public static class ExceptionHandler extends DefaultErrorWebExceptionHandler {

        public ExceptionHandler(ErrorAttributes errorAttributes,
                                WebProperties.Resources resources,
                                ErrorProperties errorProperties,
                                ApplicationContext applicationContext) {
            super(errorAttributes, resources, errorProperties, applicationContext);
        }

        /**
         * 指定响应处理方法
         */
        @Override
        protected RouterFunction<ServerResponse> getRoutingFunction(ErrorAttributes errorAttributes) {
            return RouterFunctions.route(RequestPredicates.all(), this::renderErrorResponse);
        }

        /**
         * 构建响应数据
         */
        @Override
        protected Map<String, Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace) {
            Throwable error = super.getError(request);
//            log.error("网关异常: {}", error.getMessage(), error);
            
            Map<String, Object> errorAttributes = new HashMap<>(8);
            errorAttributes.put("code", "500");
            errorAttributes.put("message", error.getMessage());
            errorAttributes.put("success", false);
            
            return errorAttributes;
        }

        /**
         * 指定响应状态码
         */
        @Override
        protected int getHttpStatus(Map<String, Object> errorAttributes) {
            return HttpStatus.OK.value();
        }

        /**
         * 构建错误响应
         */
        @Override
        protected Mono<ServerResponse> renderErrorResponse(ServerRequest request) {
            Map<String, Object> errorAttributes = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
            return ServerResponse.status(HttpStatus.valueOf(getHttpStatus(errorAttributes)))
                    .contentType(MediaType.APPLICATION_JSON)
                    .body(BodyInserters.fromValue(errorAttributes));
        }
    }
} 